package com.burningtower.service.impl;

import com.burningtower.common.Pages;
import com.burningtower.common.Result;
import com.burningtower.entity.Product;
import com.burningtower.repo.ProductRepository;
import com.burningtower.service.ProductService;
import com.burningtower.service.UserService;
import com.burningtower.utils.BeanUtil;
import com.burningtower.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2017/11/2.
 */
@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductRepository productRepository;
    @Autowired
    private UserService userService;

    /**
     * 内部使用--返回pageable
     * @param orderBy
     * @param pageNum
     * @param pageSize
     * @return Pageable
     */
     Pageable handler(String orderBy, Integer pageNum, Integer pageSize) {
        Pageable pageable = null;
        //判断是否有排序的需求
        if (orderBy!=null&&!orderBy.equals("default")) {
            String[] split = orderBy.split("_");
            if (split[1].equals("desc")) {//如果是true升序
                pageable = new PageRequest(pageNum, pageSize, new Sort(Sort.Direction.DESC, split[0]));
            } else if(split[1].equals("asc")){//否则降序
                pageable = new PageRequest(pageNum, pageSize, new Sort(Sort.Direction.ASC, split[0]));
            }else{
                throw new RuntimeException("排序参数错误");
            }

        } else {
            pageable = new PageRequest(pageNum, pageSize);
        }
        return pageable;
    }

    /**
     * 内部使用--返回page
     * @param product
     * @param pageable
     * @return Page<Product>
     */
     Page<Product> handlers(Product product,Pageable pageable) {
        Integer categoryId = product.getCategoryId();
        Integer productId = product.getId();
        String name = product.getName();

        Page<Product> page=null;
        if (name==null){//用example查询,不包含名字信息
            page = productRepository.findAll(Example.of(product), pageable);//执行查询,这里的page是原生的
        }else {//模糊查询，包含名字信息
            if (categoryId==null&&productId==null){//搜索条件只有名字
                page = productRepository.findByNameLike("%" + name + "%", pageable);
            }
            //搜索条件有名字和categoryId
            else if(categoryId!=null){
                page = productRepository.findByCategoryIdAndNameLike(categoryId, "%" + name + "%", pageable);

            }
            else if(productId!=null){//搜索条件有名字和productId
                page = productRepository.findByIdAndNameLike(productId, "%" + name + "%", pageable);

            }
        }

        return page;
    }

    /**
     *  后台根据不同条件搜索产品
     *  @param session
     *  @param pageNum
     *  @param pageSize
     *  @param orderBy
     *  @param product
     *  @return Pages<ProductVo>
     */
    @Override
    public Pages<Product> adminSearch(HttpSession session, Product product, String orderBy,
                                        Integer pageNum, Integer pageSize) {
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId==null){
            throw new RuntimeException("NEED_LOGIN");
        }
        if(userService.getUserById(userId).getRole()!=0){
            throw new RuntimeException("没有权限");
        }
        Pageable pageable = handler(orderBy, pageNum-1, pageSize);
        Page<Product> page = handlers(product, pageable);
        List<Product> list = page.getContent();//拿到page中的产品list
        // List<ProductVo> voList = new BeanUtil().change(ProductVo.class,list);//将Product对象换成productVo
        Integer total = Math.toIntExact(page.getTotalElements());
//        System.out.println(total);
        return new Pages<>(pageNum,pageSize,orderBy,list, total);
    }
    /**
     * 根据不同条件搜索产品
     */
    @Override
    public Pages<ProductVo> search( Product product, String orderBy, Integer pageNum, Integer pageSize) {
        Pageable pageable = handler(orderBy, pageNum-1, pageSize);
        Page<Product> page = handlers(product, pageable);
        List<Product> list = page.getContent();//拿到page中的产品list
        List<ProductVo> voList = new BeanUtil().change(ProductVo.class,list);//将Product对象换成productVo
        long total = page.getTotalElements();
        System.out.println(total);
        Pages<ProductVo>pages=new Pages(pageNum,pageSize,orderBy,voList, (int) total);
        return pages;
    }


    /**
     *   根据productId查询，返回单个product
     *   @param productId
     *   @return Product
     */
    @Override
    public Product get(Integer productId) {
        Product product = productRepository.findOne(productId);
        product.setImageHost("http://img.happymmall.com/");
        if ( product==null){
            throw new RuntimeException("商品不存在");
        }
        if( product.getStatus()>1){
            throw new RuntimeException("商品已删除或下架");
        }
        return product;
    }

    /**
     *  save产品
     *  @param product
     *  @return Result<String>
     */
    @Override
    public Result<String> add(Product product) {
        Result result =new Result();
        product.setCreateTime(new Date());//赋创建时间
        productRepository.save(product);
        result.setData("新增成功");
        result.setStatus(0);
        return result;

    }

    /**
     * update产品
     * @param product
     * @return Result<String>
     */
    @Override
    public Result<String> update(Product product) {
        Result result =new Result();
        product.setUpdateTime(new Date());
        Product oldProduct = productRepository.findOne(product.getId());//从数据库取出原数据
        if (oldProduct==null){
            throw new RuntimeException("更新产品失败");
        }
        product.setCreateTime(oldProduct.getCreateTime());//将创建时间，付给更新后的
        productRepository.save(product);
        result.setData("修改成功");
        result.setStatus(0);
        return result;

    }

    /**
     * 修改产品状态
     * @param product
     * @return Result<String>
     */
    @Override
    public Result<String> updateStatus(Product product) {
        Product oldProduct = productRepository.findOne(product.getId());
        oldProduct.setStatus(product.getStatus());
        productRepository.save(oldProduct);
        Result<String> result = new Result<>();
        result.setStatus(0);
        result.setData("修改产品状态成功");
        return result;
    }


}
